<?php

namespace app\mp\service;

use app\common\model\WechatUser as WechatUserModel;
use app\common\util\CacheKey;
use Firebase\JWT\JWT;
use think\facade\Cache;

/**
 * Class MpUserService
 * @package app\mp\service
 */
class MpUserService
{
    private function clearUserCache($userId)
    {
        //清空上次登录缓存，及时更新登录信息 clear 会清楚调全部缓存
        Cache::delete(CacheKey::WXMP . "#" . $userId);
    }

    /**
     * @param $mpUser
     * @return array/**
     * {
     * "id": "ocXcn1CnkmswJQ_kZwstHkWi4P8E",
     * "name": "吉芳-软件开发",
     * "nickname": "吉芳-软件开发",
     * "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/HIX2DsmfmSUCtSZzM5sCx11bHzcPjMrRBAFa2BHApyu85CGDvcDiaBibXUSANUh7AvaftCgiaUntgDLicN1nb7XSmQ/132",
     * "email": null,
     * "raw": {
     * "openid": "ocXcn1CnkmswJQ_kZwstHkWi4P8E",
     * "nickname": "吉芳-软件开发",
     * "sex": 1,
     * "language": "zh_CN",
     * "city": "深圳",
     * "province": "广东",
     * "country": "中国",
     * "headimgurl": "https://thirdwx.qlogo.cn/mmopen/vi_32/HIX2DsmfmSUCtSZzM5sCx11bHzcPjMrRBAFa2BHApyu85CGDvcDiaBibXUSANUh7AvaftCgiaUntgDLicN1nb7XSmQ/132",
     * "privilege": []
     * },
     * "access_token": "38_wfrSS3a3X-O3l-1oXMwKvO7O0w287hY2XN2trzAJS6d_eghI16V8Er96UrmjztjcTw3HxspEkCv04JqNz7sziQ",
     * "refresh_token": "38_Ka6r2t6Jqeq0KLGaGDYE8RHbySG4b2HEC0zeY4UUFdAzvYgoomykGveyv5HhtdpfT3TDwL8O2VXExA6Qsc0g_g",
     * "expires_in": 7200
     * }
     * @throws \Exception
     */
    public function login($mpUser)
    {
        if (empty($mpUser['id'])) {
            throw new \Exception('登录失败');
        }
        $loginTime = date('Y-m-d H:i:s');
        //处理用户数据
        $condition = ['openid' => $mpUser['id']];
        $user = WechatUserModel::where($condition)->find();
        if (!$user) {
            $updateData = [];
            $updateData['nick_name'] = empty($mpUser['nickname']) ? '' : $mpUser['nickname'];
            $updateData['gender'] = empty($mpUser['raw']['sex']) ? '' : $mpUser['raw']['sex'];
            $updateData['language'] = empty($mpUser['raw']['language']) ? '' : $mpUser['raw']['language'];
            $updateData['country'] = empty($mpUser['raw']['country']) ? '' : $mpUser['raw']['country'];
            $updateData['province'] = empty($mpUser['raw']['province']) ? '' : $mpUser['raw']['province'];
            $updateData['city'] = empty($mpUser['raw']['city']) ? '' : $mpUser['raw']['city'];
            $updateData['avatar_url'] = empty($mpUser['raw']['headimgurl']) ? '' : $mpUser['raw']['headimgurl'];
            $updateData['openid'] = $mpUser['id'];
            $updateData['login_time'] = $loginTime;
            $user = WechatUserModel::create($updateData);
        } else {
            $user->login_time = $loginTime;
            $user->save();
        }

        $expire = 3600 * 2;
        $time = time();
        $payload = array(
            'exp' => $time + $expire,
            "id" => $user->id,
            't' => 'mp' //
        );
        $jwtKey = env('jwt.key');
        $token = JWT::encode($payload, $jwtKey);
        $refreshPayload = [
            'exp' => $time + 3600 * 24 * 7,
            'id' => $user->id,
            't' => 'wxapp'
        ];
        $refreshToken = JWT::encode($refreshPayload, $jwtKey);

        $this->clearUserCache($user->id);

        return ['token' => $token, 'refresh_token' => $refreshToken];
    }

}